package com.zlcx.tz.live.web;

import com.alibaba.fastjson.JSON;
import com.zlcx.tz.live.client.UserClient;
import com.zlcx.tz.live.common.annotation.AutoLog;
import com.zlcx.tz.live.common.annotation.RepeatSubmit;
import com.zlcx.tz.live.constant.YN;
import com.zlcx.tz.live.domain.LiveAgoraAcount;
import com.zlcx.tz.live.domain.LiveRoomPublisherRecord;
import com.zlcx.tz.live.exception.BusinessException;
import com.zlcx.tz.live.exception.CheckParamException;
import com.zlcx.tz.live.exception.CheckRunException;
import com.zlcx.tz.live.exception.SendExceptionUtil;
import com.zlcx.tz.live.service.impl.LiveAgoraAcountService;
import com.zlcx.tz.live.service.impl.LiveRoomPublisherService;
import com.zlcx.tz.live.service.impl.LiveRoomService;
import com.zlcx.tz.live.vo.AgoraAcountVO;
import com.zlcx.tz.live.vo.ResultVO;
import com.zlcx.tz.live.vo.StatusVO;
import com.zlcx.tz.live.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p></p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author zl
 * @version 1.0
 * @date Created in 2019/5/22 09:09
 * @copyright: Copyright (c) founders
 */
@Controller
@Slf4j
@Api(tags = {"声网账号"}, description = "声网账号相关接口")
@RequestMapping("acount")
public class LiveAgoraAcountController extends BaseController {

    @Autowired
    private LiveAgoraAcountService liveAgoraAcountService;

    @Autowired
    LiveRoomPublisherService publisherService;

    @Resource(name = "taskExecutor")
    AsyncTaskExecutor asyncTaskExecutor;

    @Autowired
    LiveRoomService liveRoomService;

    @Autowired
    UserClient userClient;

    @Autowired
    private LiveRoomPublisherService liveRoomPublisherService;


    @Autowired
    private SendExceptionUtil emailService;

    private Logger traceLoger = LoggerFactory.getLogger("traceloger");

    @AutoLog
    @ApiOperation(value = "获取当前账号信息", notes = "获取当前账号信息", response = AgoraAcountVO.class, responseContainer = "Map")
    @GetMapping(value = "/current")
    public ResponseEntity<ResultVO> current(@ApiParam(value = "token", required = false) @RequestHeader(required = false) String authorization,
                                            @ApiParam(value = "version") @RequestHeader(required = false) String version) {

        Long userId = currentUserId();
        log.debug("用户启动app，userId={}", userId);
        try {
            ResultVO resultVO = successState();
            if (Objects.nonNull(userId)) {
                checkUserStatus(userId);
            }
            LiveAgoraAcount liveAgoraAcount = liveAgoraAcountService.getCurrentUseAcountCache();
            resultVO.setData(liveAgoraAcount);
            return ResponseEntity.ok(resultVO);

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("获取当前账号信息失败", e);
            throw new CheckRunException("获取当前账号信息失败!", e);
        }

    }

    @AutoLog
    @ApiOperation(value = "检查用户房间状态，如果是连麦中，直接踢出房间", notes = "检查用户房间状态，如果是连麦中，直接踢出房间", response = AgoraAcountVO.class, responseContainer = "Map")
    @GetMapping(value = "/checkUserStatus")
    public ResponseEntity<ResultVO> checkUserStatus(Long userId) {
        if (userId == null) {
            return null;
        }
        asyncTaskExecutor.execute(() -> {
            try {
                StatusVO statusVO = publisherService.statusInfo(userId, null);
                UserVO userInfo = userClient.findOne(userId).getData();
                log.info("用户启动app，查询上次状态，statusVO={} 用户信息 userInfo = {}", JSON.toJSONString(statusVO), userInfo);
                Long roomId = statusVO.getRoomId();

                if (YN.NO.getCode() == statusVO.getInRoomState()) {
                    //3表示用户连麦中
                    if (userInfo.getStatus().equals(UserVO.StatusEnums.LIVE_LEARNING.code)) {
                        log.info("用户连麦学习中，进行状态重置！userInfo = {}", userInfo);
                        LiveRoomPublisherRecord publishingRecord = liveRoomPublisherService.getLastPublishingRecord(userId);
                        if (Objects.isNull(publishingRecord)) {
                            throw new NullPointerException("连麦学习异常，用户状态 ：连麦中，无法查询到用户最新的连麦的上麦记录！userId = " + userId);
                        }
                        liveRoomPublisherService.forceStopLearnTask(publishingRecord);
                    }
                } else {
                    traceLoger.info("【用户启动app】 用户【{}】房间【{}】重置上次未退出的房间 ", userId, roomId);
                    liveRoomService.exitRoom(userId, roomId, false, true);
                }

            } catch (CheckParamException | NullPointerException e) {
                log.error("启动app查询上次状态异常", e);
            } catch (Exception e) {
                log.error("启动app查询上次状态异常", e);
                emailService.sendException("启动app, 连麦状态检查异常 " + e.getMessage(), e);
            }

        });

        return null;
    }

    @AutoLog
    @RepeatSubmit
    @ApiOperation(value = "切换成当前AppId", notes = "切换成当前AppId")
    @PostMapping(value = "/activeAppid/{appId}")
    public ResponseEntity<ResultVO> activeAppid(
            @ApiParam(value = "AppId", required = true) @PathVariable String appId
    ) {

        try {
            liveAgoraAcountService.activeAppid(appId);
            return ResponseEntity.ok(successState());

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("切换成当前AppId失败，appId={}", appId, e);
            throw new CheckRunException("切换成当前AppId失败!", e);
        }

    }


}
